/*
 * @Description: IM hook
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2025-04-17
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2025-04-29
 */
import { requestGetServerInfo, requestOffLine } from '../api/im'
import { requestChatImMessagePage, requestImMessagePage, requestSendChatMsg } from '../api/imMessage'
import { MsgTypeEnum } from '../api/imMessage/enum'
import { ConnectStatusEnum } from '../enum'
import { IMConfig, IMTextMsg } from '../type'
import Socket from './socket'

export const useIM = (config?: IMConfig) => {
  const { connectConfig = { userId: '', userName: '' }, onConnectStatus = () => {}, onMessage = () => {}, onError = () => {} } = config ?? {}

  /** 用户信息 */
  const { userId, userName } = connectConfig

  /**
   * 校验参数
   * @returns
   */
  const validConfig = () => {
    console.log('userId:', userId, ', userName:', userName) //TODO

    if (!userId) {
      console.log('缺少参数: userId')
      return false
    }
    if (!userName) {
      console.log('缺少参数: userName')
      return false
    }
    return true
  }

  /**
   * 获取im服务地址
   * @returns
   */
  const getImAddress = async () => {
    const { responseData } = await requestGetServerInfo({ userId, userName })
    const { ip, webSocketPort } = responseData
    return `ws://${ip}:${webSocketPort}/webSocket`
  }

  /**
   * 连接IM
   */
  const connectIM = async () => {
    if (!validConfig()) return

    await requestOffLine({ userId })

    const url = await getImAddress()
    Socket.init({
      url,
      userId,
      onOpen: () => onConnectStatus(ConnectStatusEnum.OPEN),
      onMessage: (res) => onMessage(JSON.parse(res.data ?? '{}')),
      onClose: () => onConnectStatus(ConnectStatusEnum.CLOSED),
      onError: (err) => onError(err),
    })

    Socket.connect()
  }

  /**
   * 关闭IM
   */
  const closeIM = () => Socket.close()

  /**
   * 发送文本消息
   * @param msg 消息内容
   * @param toId 对方id
   */
  const sendTextMsg = async ({ msg, toId }: IMTextMsg) => {
    const res = await requestSendChatMsg({ content: msg, msgType: MsgTypeEnum.TEXT_MSG, extStr: '', recipientId: toId })
    return res
  }

  /**
   * 获取聊天成员列表
   * @returns
   */
  const getChatMembers = async () => {
    const { responseData } = await requestImMessagePage({ pageIndex: 1, pageSize: 999 })
    return responseData.list
  }

  /**
   * 获取聊天消息
   * @param senderId 发送人id
   * @param recipientId 接收人id
   * @returns
   */
  const getChatMessages = async ({ senderId, recipientId }) => {
    const { responseData } = await requestChatImMessagePage({ senderId, recipientId, pageIndex: 1, pageSize: 999 })
    return responseData.list
  }

  return {
    connectIM,
    closeIM,
    sendTextMsg,
    getChatMembers,
    getChatMessages,
  }
}

export default useIM
